package com.scitc.pleasurevideo;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.githang.statusbar.StatusBarCompat;
import com.jaeger.library.StatusBarUtil;
import com.scitc.pleasurevideo.adapter.VideoSelectPlayAdapter;
import com.scitc.pleasurevideo.base.ETActivity;
import com.scitc.pleasurevideo.data.CollectTvDataMan;
import com.scitc.pleasurevideo.data.ETMan;
import com.scitc.pleasurevideo.data.HistoryTvDataMan;
import com.scitc.pleasurevideo.dialog.DialogSettingRadio;
import com.scitc.pleasurevideo.dialog.DialogSettingRadioAndRemaber;
import com.scitc.pleasurevideo.dialog.DialogUtils;
import com.scitc.pleasurevideo.helper.ForwardHelper;
import com.scitc.pleasurevideo.helper.ThreadHelper;
import com.scitc.pleasurevideo.imgutil.ImageManager;
import com.scitc.pleasurevideo.pojo.CachingTvVo;
import com.scitc.pleasurevideo.pojo.DoubanTvVo;
import com.scitc.pleasurevideo.pojo.MenuTvVo;
import com.scitc.pleasurevideo.pojo.PlayMenuTvVo;
import com.scitc.pleasurevideo.util.AndroidUtil;
import com.scitc.pleasurevideo.util.AtyContainer;
import com.scitc.pleasurevideo.util.ConstUtil;
import com.scitc.pleasurevideo.util.GetHtmlContentUtil;
import com.scitc.pleasurevideo.util.SearchTvUtil;
import com.scitc.pleasurevideo.util.UIHelper;
import com.scitc.pleasurevideo.view.CollapsibleTextView;
import com.scitc.pleasurevideo.view.SwDialog;
import com.scitc.pleasurevideo.view.VideoPlayerView;
import com.scitc.pleasurevideo.x5webview.MyApplication;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.cache.CacheFactory;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.player.PlayerFactory;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;

import java.util.ArrayList;
import java.util.List;

import tv.danmaku.ijk.media.exo2.Exo2PlayerManager;
import tv.danmaku.ijk.media.exo2.ExoPlayerCacheManager;

/**
 * @author contradiction
 */
public class PlayVideoActivity extends ETActivity {

    private OrientationUtils orientationUtils;
    private List<PlayMenuTvVo> items = new ArrayList<>();
    private VideoSelectPlayAdapter madapter;
    private VideoPlayerView videoPlayer;
    private ImageView ivVideo;
    private ImageView imageView;
    private ImageView igCollect;
    private ImageView igDownload;
    private TextView tvVideoInfo;
    private RecyclerView rlvVideo;
    private TextView headerTitle;
    private TextView tvDirector;
    private TextView tvProtagonist;
    private LinearLayout llBigBox;

    private MenuTvVo menuTvPojo;
    private DoubanTvVo doubanTvPojo;
    private Boolean isHeadImg = false;
    private RelativeLayout rlImgVideoPause;
    private TextView tvSubtitle;
    private TextView tvOpenCollect;

    private CachingTvVo cachingTvVo = new CachingTvVo();
    private Boolean isSaveHistory = false;
    private int oldIgImageHeight;
    private View mTopView;
    private boolean isFrisetVideoPlayer = true;
    private boolean isFullSerccen = false;
    private boolean isFullSercenClickNext = false;
    private String tvIntroductionString;
    private int saveHistoryType=-1;
    private boolean userIsSaveHistory=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(mInstance, R.color.black), true);
        StatusBarUtil.setDarkMode(mInstance);

        menuTvPojo = (MenuTvVo) getIntent().getSerializableExtra("menuTvPojo");
        doubanTvPojo = (DoubanTvVo) getIntent().getSerializableExtra("doubanTvPojo");
        initView();
        onClick();
        load();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                fristInJudge();
            }
        },300);
    }

    /**
     * 进入界面 加载数据
     */
    private void load() {
        //判断这么进行加载数据
        List<PlayMenuTvVo> temps = (List<PlayMenuTvVo>) getIntent().getSerializableExtra("items");
        if (temps == null || temps.size() < 1) {
            loadData();
        } else {
            setTextView(temps.get(0), temps.size());
            madapter.addAll(temps);
            madapter.setPosition(temps.get(0).getPlaySetInt());
            rlvVideo.scrollToPosition(temps.get(0).getPlaySetInt());
        }
    }

    /**
     * 加载网络数据
     */
    private void loadData() {
        //判断有没有图片
        if (!isHeadImg) {
            ThreadHelper.run(() -> SearchTvUtil.searchTvImg(mInstance, menuTvPojo.getUrl() + menuTvPojo.getPlayerString()));
        }
        //搜索到图片的回调
        SearchTvUtil.setOnSecrchName(new SearchTvUtil.OnSecrchName() {
            @Override
            public void setOnSearchName(String name) {

            }

            @Override
            public void setOnSearchImg(String url) {
                if (!isHeadImg) {
                    runOnUiThread(() -> {
                        ImageManager.bindImageCenterCrop(mInstance, ivVideo, url);
                        ImageManager.bindRoundedCornersImageCenterCrop(mInstance, imageView, url, 4);
                        doubanTvPojo.setCover(url);
                        isHeadImg = true;
                    });
                }
            }
        });

//        使用jsoup爬取 能获取  web播放地址 m3u8播放地址 MP4播放地址 只要有
        GetHtmlContentUtil.getPlayMenuTvList(mInstance, menuTvPojo.getUrl() + menuTvPojo.getPlayerString());
        GetHtmlContentUtil.getPlayMenuTvList(new GetHtmlContentUtil.GetPlayMenuTvList() {
            @Override
            public void playmenuTvList(List<PlayMenuTvVo> playMenuTvPojoList) {
                madapter.addAll(playMenuTvPojoList);
                setTextView(playMenuTvPojoList.get(0), playMenuTvPojoList.size());
            }

            @Override
            public void playmenuTv(PlayMenuTvVo playMenuTvPojo) {
                if (madapter.getCount() > 0) {
                    setTextView(madapter.getItem(0), madapter.getCount());
                } else {
                    setTextView(playMenuTvPojo, madapter.getCount());
                }
                madapter.addItem(playMenuTvPojo);
            }
        });

    }

    /**
     * 设置视频的简介和一些信息
     *
     * @param playMenuTvPojo
     * @param count
     */
    private void setTextView(PlayMenuTvVo playMenuTvPojo, Integer count) {
        String temp = "<font color=\"#1F1F1F\">共有：</font>" + count + "集";
        tvVideoInfo.setText(Html.fromHtml(temp));
        temp = playMenuTvPojo.getDirector().replace("导演：", "<font color=\"#1F1F1F\">导演：</font>");
        tvDirector.setText(Html.fromHtml(temp));
        temp = playMenuTvPojo.getProtagonist().replace("主演：", "<font color=\"#1F1F1F\">主演：</font>");
        tvProtagonist.setText(Html.fromHtml(temp));
        temp = playMenuTvPojo.getSubtitle().replace("简介：", "<font color=\"#1F1F1F\">简介：</font>");
        tvIntroductionString=temp;
        tvSubtitle.setText(Html.fromHtml(tvIntroductionString));
        if(tvIntroductionString.length()>120){
            tvOpenCollect.setVisibility(View.VISIBLE);
        }else {
            tvOpenCollect.setVisibility(View.GONE);
        }
        new Handler().postDelayed(() -> checkCollect(),500);
        initDownloadUI();
    }

    /**
     * 点击事件
     */
    private void onClick() {
        madapter.setOnClickItemListener(this::judgeIsCanPlay);
        rlImgVideoPause.setOnClickListener(view -> judgeIsCanPlay(madapter.getPosition(), madapter.getItems()));
        //视频播放进度的回调
        videoPlayer.setGSYVideoProgressListener((progress, secProgress, currentPosition, duration) -> {
//                Log.e("PlayVideoActivity", progress + "," + secProgress + "," + currentPosition + "," + duration);
            MyApplication.setPlayTimeSecondAdd();
            toSaveVideoSchedule(currentPosition, duration);
        });
        //查看简介
        tvOpenCollect.setOnClickListener(view -> {
            if ("[点击展开]".equals(tvOpenCollect.getText().toString())) {
                tvOpenCollect.setText("[点击收缩]");
                tvSubtitle.setMaxLines(2000);
                tvSubtitle.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10000)});
                tvSubtitle.setText(Html.fromHtml(tvIntroductionString));
            } else {
                tvOpenCollect.setText("[点击展开]");
                tvSubtitle.setMaxLines(4);
                tvSubtitle.setFilters(new InputFilter[]{new InputFilter.LengthFilter(120)});
                tvSubtitle.setText(Html.fromHtml(tvIntroductionString));
            }
        });
        //点击了收藏
        igCollect.setOnClickListener(view -> {
            igCollect.setClickable(false);
            onClickCollect();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    igCollect.setClickable(true);
                }
            },500);
        });
        //点击了下载
        igDownload.setOnClickListener(view -> {
            Toast.makeText(mInstance, "点击了下载", Toast.LENGTH_SHORT).show();
        });

        //设置全屏按键功能
        videoPlayer.getFullscreenButton().setOnClickListener(view -> {
            isFullSerccen = true;
            setFullSerccenTrue();
        });

        //设置返回按键功能
        videoPlayer.getBackButton().setOnClickListener(view -> onBackPressed());

        //视频的下一集按钮点击
        videoPlayer.getIgVideoNextBtn().setOnClickListener(view -> {
            if (madapter.getPosition() >= madapter.getCount()) {
                Toast.makeText(mInstance, "已经是最后一个视频了", Toast.LENGTH_SHORT).show();
            } else {
                judgeIsCanPlay(madapter.getPosition() + 1, madapter.getItems());
                isFullSercenClickNext = true;
            }
        });

        //视频的列表点击
        videoPlayer.getLvVideoMenu().setOnItemClickListener((parent, view, position, id) -> {
            if (position == madapter.getPosition()) {
                Toast.makeText(mInstance, "正在播放", Toast.LENGTH_SHORT).show();
            } else {
                judgeIsCanPlay(position, madapter.getItems());
                videoPlayer.getLvVideoMenu().setVisibility(View.GONE);
                isFullSercenClickNext = true;
            }
        });
    }

    /**
     * 设置全屏播放
     */
    private void setFullSerccenTrue() {
        orientationUtils.resolveByClick();
        getWindow().getDecorView().setSystemUiVisibility(View.GONE);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) videoPlayer.getLayoutParams();
        params.height = LinearLayout.LayoutParams.MATCH_PARENT;
        params.width = LinearLayout.LayoutParams.MATCH_PARENT;
        videoPlayer.setLayoutParams(params);
        videoPlayer.getFullscreenButton().setVisibility(View.GONE);
        videoPlayer.getIgVideoNextBtn().setVisibility(View.VISIBLE);
        videoPlayer.getIgVideoSpeed().setVisibility(View.VISIBLE);
        videoPlayer.setIgVideoMenuBtnVisitible(View.VISIBLE);
        mTopView.setVisibility(View.GONE);
        mInstance.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 退出全部播放
     */
    private void setFullSerccenFalse() {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) videoPlayer.getLayoutParams();
        params.height = oldIgImageHeight;
        videoPlayer.setLayoutParams(params);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.black), true);
        StatusBarUtil.setDarkMode(mInstance);
        mTopView.setVisibility(View.VISIBLE);
        videoPlayer.getFullscreenButton().setVisibility(View.VISIBLE);
        videoPlayer.getIgVideoNextBtn().setVisibility(View.GONE);
        videoPlayer.setIgVideoMenuBtnVisitible(View.GONE);
        videoPlayer.getLvVideoMenu().setVisibility(View.GONE);
        videoPlayer.getIgVideoSpeed().setVisibility(View.GONE);
        mInstance.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 判断能不能播放
     * @param position
     * @param items
     */
    private void judgeIsCanPlay(int position, List<PlayMenuTvVo> items){
        if(!AndroidUtil.isNetworkConnected(mInstance)){
            Toast.makeText(mInstance, "网络连接失败", Toast.LENGTH_SHORT).show();
        }else if(AndroidUtil.isWifiAccess(mInstance)||ETMan.getPref(mInstance,ConstUtil.IS_FLOW_PLAY_VIDEO,false)){
            toPlayVideo(position,items);
        }else {
            String title = "确定打开2G/3G/4G网络播放开关吗？";
            String text = "使用2G/3G/4G网络播放会消耗流量，请慎重设置";
            DialogUtils.showConfirmNormalDia(title, text, "打开播放开关", "取消播放", this, v -> {
                ETMan.savePref(mInstance,ConstUtil.IS_FLOW_PLAY_VIDEO,true);
                toPlayVideo(position,items);
            });
        }
    }
    /**
     * 点击了视频列表，进行判断怎么播放
     *
     * @param position
     * @param items
     */
    private void toPlayVideo(int position, List<PlayMenuTvVo> items) {
        if (items == null || items.size() < 1) {
            return;
        }
        toPlayVideoUI(position,items);
        String url;
        if (items.get(position).getPlayMp4Url() != null && items.get(position).getPlayMp4Url().indexOf("mp4") > 0) {
            url = items.get(position).getPlayMp4Url();
        } else if (items.get(position).getPlayM3u8Url() != null && items.get(position).getPlayM3u8Url().indexOf("m3u8") > 0) {
            url = items.get(position).getPlayM3u8Url();
        } else {
            ForwardHelper.toWebviewPlayActivity(mInstance, items.get(position).getPlayWebUrl(), doubanTvPojo.getTitle());
            toSaveSP(items, position);
            return;
        }
        toSaveSP(items, position);

        //设置播放速度为默认
        videoPlayer.setVideoSpeedDefalut();
        //设置触摸后自动隐藏其他控件的时间
        videoPlayer.setDismissControlTime(5000);

        if (isFrisetVideoPlayer) {
            initPlayer(url, doubanTvPojo.getTitle(), items.get(position).getName(), position);
            isFrisetVideoPlayer=false;
        } else {
            videoPlayer.setUp(url, true, doubanTvPojo.getTitle() + items.get(position).getName());
            videoPlayer.setVideoMenuPosition(position);
            videoPlayer.setRlMoreSeetingGone();
        }
    }

    /**
     * 播放视频的时候，设置怎样显示ui
     * @param position
     * @param items
     */
    private void toPlayVideoUI(int position, List<PlayMenuTvVo> items){
        if (position >= (items.size() - 1)) {
            videoPlayer.getIgVideoNextBtn().setImageResource(R.mipmap.ic_video_next_no);
            videoPlayer.getIgVideoNextBtn().setClickable(false);
        } else {
            videoPlayer.getIgVideoNextBtn().setImageResource(R.mipmap.ic_video_next);
            videoPlayer.getIgVideoNextBtn().setClickable(true);
        }
        rlImgVideoPause.setVisibility(View.GONE);
        videoPlayer.setVisibility(View.VISIBLE);
        videoPlayer.setSeekOnStart(items.get(position).getCurrentPosition().longValue());
        madapter.setPosition(position);
    }

    /**
     * 初始化数据
     */
    private void initView() {
        headerTitle = (TextView) findViewById(R.id.headerTitle);
        llBigBox = (LinearLayout) findViewById(R.id.llBigBox);
        mTopView = findViewById(R.id.topView);
        headerTitle.setText(doubanTvPojo.getTitle());
        tvDirector = (TextView) findViewById(R.id.tvDirector);
        tvProtagonist = (TextView) findViewById(R.id.tvProtagonist);
        tvSubtitle = (TextView) findViewById(R.id.tvSubtitle);
        tvOpenCollect = (TextView) findViewById(R.id.tvOpenCollect);
        rlImgVideoPause = (RelativeLayout) findViewById(R.id.rlImgVideoPause);
        videoPlayer = (VideoPlayerView) findViewById(R.id.video_player);
        ivVideo = (ImageView) findViewById(R.id.iv_video);
        igCollect = (ImageView) findViewById(R.id.igCollect);
        igDownload = (ImageView) findViewById(R.id.igDownload);
        imageView = (ImageView) findViewById(R.id.imageView);
        tvVideoInfo = (TextView) findViewById(R.id.tv_video_info);
        rlvVideo = (RecyclerView) findViewById(R.id.rlv_video);
        rlvVideo.setLayoutManager(new GridLayoutManager(this, 2));
        madapter = new VideoSelectPlayAdapter(mInstance, items);
        rlvVideo.setAdapter(madapter);


        //判断有没有图片
        if (TextUtils.isEmpty(doubanTvPojo.getCover()) ||
                doubanTvPojo.getCover().toLowerCase().equals("null".toLowerCase()) ||
                doubanTvPojo.getCover().trim().length() < 1) {
            isHeadImg = false;
        } else {
            ImageManager.bindImageCenterCrop(this, ivVideo, doubanTvPojo.getCover());
            ImageManager.bindRoundedCornersImageCenterCrop(this, imageView, doubanTvPojo.getCover(), 4);
             isHeadImg = true;
        }
        setImageAndVideoHeight();
        setTopViewHeight();
    }

    /**
     * 设置头部代替状态栏的topview的高度
     */
    private void setTopViewHeight() {
        runOnUiThread(() -> {
            int resourceId = mInstance.getResources().getIdentifier("status_bar_height", "dimen", "android");
            int topHeight = mInstance.getResources().getDimensionPixelSize(resourceId);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mTopView.getLayoutParams();
            layoutParams.height = topHeight;
            mTopView.setLayoutParams(layoutParams);
        });
    }

    /**
     * 设置视频的宽高是16：9
     */
    private void setImageAndVideoHeight() {
        runOnUiThread(() -> {
            int imageWidth = UIHelper.getScreenWidth(mInstance);
            double iWidth = imageWidth / 16.0;
            int nHeight = Double.valueOf(iWidth * 9.0).intValue();
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) videoPlayer.getLayoutParams();
            layoutParams.height = nHeight;
            oldIgImageHeight = nHeight;
            videoPlayer.setLayoutParams(layoutParams);
            rlImgVideoPause.setLayoutParams(layoutParams);
            RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) ivVideo.getLayoutParams();
            layoutParams1.height = nHeight;
            ivVideo.setLayoutParams(layoutParams1);
        });
    }


    /**
     * 初始化播放
     *
     * @param source
     * @param videoName
     * @param nameNumber
     */
    private void initPlayer(String source, String videoName, String nameNumber, int postion) {
        PlayerFactory.setPlayManager(Exo2PlayerManager.class);
        CacheFactory.setCacheManager(ExoPlayerCacheManager.class);
        videoPlayer.setUp(source, true, videoName + nameNumber);
        //增加Title
        videoPlayer.getTitleTextView().setVisibility(View.VISIBLE);
        //设置返回键
        videoPlayer.getBackButton().setVisibility(View.VISIBLE);
        //设置旋转
        orientationUtils = new OrientationUtils(this, videoPlayer);
        //是否可以滑动调整
        videoPlayer.setIsTouchWiget(true);
        //初始化视频播放列表
        videoPlayer.addAllVideoMenu(madapter.getItems());
        PlayerFactory.setPlayManager(Exo2PlayerManager.class);
        CacheFactory.setCacheManager(ExoPlayerCacheManager.class);
        videoPlayer.startPlayLogic();
        videoPlayer.setVideoMenuPosition(postion);
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    /**
     * 结束时，清除一些数据
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (isSaveHistory) {
            saveHistoryData();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isSaveHistory) {
            saveHistoryData();
        }
    }

    /**
     * 触发了返回键
     */
    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    public void onBackPressed() {
        //先返回正常状态
        if (isFullSerccen) {
            isFullSerccen = false;
            setFullSerccenFalse();
            videoPlayer.setRlMoreSeetingGone();
            if (isFullSercenClickNext) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                isFullSercenClickNext = false;
            } else {
                orientationUtils.resolveByClick();
            }
            return;
        }
        //释放所有
        videoPlayer.setVideoAllCallBack(null);
        super.onBackPressed();
    }

    /**
     * 播放的哪一集视频 进行保存
     * 历史
     * @param items
     * @param position
     */
    private void toSaveSP(List<PlayMenuTvVo> items, int position) {
        isSaveHistory = true;
        cachingTvVo.setImgUrl(doubanTvPojo.getCover());
        cachingTvVo.setAllSet("共" + madapter.getCount() + "集");
        cachingTvVo.setPlaySet("看到:第" + (position + 1) + "集");
        cachingTvVo.setName(doubanTvPojo.getTitle());
        cachingTvVo.setHtmlTitle(menuTvPojo.getTitle());
        cachingTvVo.setUrl(menuTvPojo.getUrl());
        cachingTvVo.setSubtitle(tvSubtitle.getText().toString());
        cachingTvVo.setPalyListUrl(menuTvPojo.getPlayerString());
        items.get(0).setPlaySetInt(position);
        cachingTvVo.setPlayMenuTvPojos(items);
        updateCollect(cachingTvVo);
    }

    /**
     * 保存视频播放的进度
     *
     * @param currentPosition
     * @param duration
     */
    private void toSaveVideoSchedule(int currentPosition, int duration) {
        if (madapter.getCurrentPosition() < 1) {
            saveHistoryData();
        } else if (currentPosition - madapter.getCurrentPosition() > 10000) {
            saveHistoryData();
        }
        madapter.setHistorySchedule(currentPosition, duration);
    }

    /**
     * 判断是否允许保存历史记录
     */
    private void saveHistoryData(){
        updateCollect(cachingTvVo);
        boolean judgeIsSave=ETMan.getPref(mInstance,ConstUtil.IS_SAVE_PLAY_HISTORY_LIST,true);
        if(judgeIsSave && userIsSaveHistory){
            HistoryTvDataMan.getHistoryTvDataMan().saveHistoryTvDataMan(cachingTvVo,saveHistoryType);
        }
    }

    /**
     * 第一次进入界面，进行判断是否提醒用户历史记录的保存方式
     */
    private void fristInJudge(){
        int saveType=ETMan.getPref(mInstance, ConstUtil.IS_HISTORY_DIFFERENT_SOURCE, ConstUtil.HISTORY_TYPE_DEFAULT);
        if(saveType==ConstUtil.HISTORY_TYPE_ARRAY.length-1){
            toAlertDialog();
        }
    }

    /**
     * 弹出历史记录 如何保存的选择dialog
     */
    private void toAlertDialog(){
        String[] array={"共存","替换","不保存"};
        new DialogSettingRadioAndRemaber(llBigBox, mInstance, "历史记录", array, selectandisremember -> {
            String[] items=selectandisremember.split(",");
            if("0".equals(items[0])){
                saveHistoryType=0;
                userIsSaveHistory=true;
                if("true".equals(items[1])){
                    ETMan.savePref(mInstance, ConstUtil.IS_HISTORY_DIFFERENT_SOURCE, 0);
                }
            }else if("1".equals(items[0])){
                saveHistoryType=1;
                userIsSaveHistory=true;
                if("true".equals(items[1])){
                    ETMan.savePref(mInstance, ConstUtil.IS_HISTORY_DIFFERENT_SOURCE, 1);
                }
            }else {
                saveHistoryType=-1;
                userIsSaveHistory=false;
                if("true".equals(items[1])){
                    ETMan.savePref(mInstance,ConstUtil.IS_SAVE_PLAY_HISTORY_LIST,false);
                }
            }
        });
    }

    /**
     * 是否更新收藏记录
     * @param newData
     */
    private void updateCollect(CachingTvVo newData){
        CachingTvVo cachingTvVo=getCollect();
        if(CollectTvDataMan.getCollectTvDataMan().isHave(cachingTvVo)){
            CollectTvDataMan.getCollectTvDataMan().updateTvVo(cachingTvVo,newData);
        }
    }

    /**
     * 点击收藏按钮
     */
    private void onClickCollect(){
        CachingTvVo cachingTvVo=getCollect();
        if(CollectTvDataMan.getCollectTvDataMan().isHave(cachingTvVo)){
            CollectTvDataMan.getCollectTvDataMan().deleteCachingTvVo(cachingTvVo);
            Toast.makeText(this, "已移除收藏", Toast.LENGTH_SHORT).show();
            igCollect.setImageResource(R.mipmap.ic_collect_off);
        }else {
            CollectTvDataMan.getCollectTvDataMan().saveCollectDataMan(cachingTvVo);
            Toast.makeText(this, "已添加收藏", Toast.LENGTH_SHORT).show();
            igCollect.setImageResource(R.mipmap.ic_collect_on);
        }
    }

    /**
     * 检查是否已收藏
     */
    private void checkCollect(){
        CachingTvVo cachingTvVo=getCollect();
        if(CollectTvDataMan.getCollectTvDataMan().isHave(cachingTvVo)){
            igCollect.setImageResource(R.mipmap.ic_collect_on);
        }else {
            igCollect.setImageResource(R.mipmap.ic_collect_off);
        }
        igCollect.setVisibility(View.VISIBLE);
    }

    /**
     * 获取收藏的信息
     * @return
     */
    private CachingTvVo getCollect(){
        CachingTvVo cachingTvVo=new CachingTvVo();
        cachingTvVo.setImgUrl(doubanTvPojo.getCover());
        cachingTvVo.setName(doubanTvPojo.getTitle());
        cachingTvVo.setHtmlTitle(menuTvPojo.getTitle());
        cachingTvVo.setSubtitle(tvSubtitle.getText().toString());
        cachingTvVo.setUrl(menuTvPojo.getUrl());
        cachingTvVo.setPalyListUrl(menuTvPojo.getPlayerString());
        return cachingTvVo;
    }

    /**
     * 判断是否显示下载ui
     */
    private void initDownloadUI() {
        if(MyApplication.isShowDownloadUi){
            igDownload.setVisibility(View.VISIBLE);
            igDownload.setClickable(false);
        }else {
            igDownload.setVisibility(View.INVISIBLE);
        }
    }
}
